{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n********************************\nChoosing Colormaps in Matplotlib\n********************************\n\nMatplotlib has a number of built-in colormaps accessible via\n`.matplotlib.cm.get_cmap`.  There are also external libraries like\n[palettable]_ and [colorcet]_ that have many extra colormaps.\nHere we briefly discuss how to choose between the many options.  For\nhelp on creating your own colormaps, see\n:doc:`/tutorials/colors/colormap-manipulation`.\n\nOverview\n========\n\nThe idea behind choosing a good colormap is to find a good representation in 3D\ncolorspace for your data set. The best colormap for any given data set depends\non many things including:\n\n- Whether representing form or metric data ([Ware]_)\n\n- Your knowledge of the data set (*e.g.*, is there a critical value\n  from which the other values deviate?)\n\n- If there is an intuitive color scheme for the parameter you are plotting\n\n- If there is a standard in the field the audience may be expecting\n\nFor many applications, a perceptually uniform colormap is the best\nchoice --- one in which equal steps in data are perceived as equal\nsteps in the color space. Researchers have found that the human brain\nperceives changes in the lightness parameter as changes in the data\nmuch better than, for example, changes in hue. Therefore, colormaps\nwhich have monotonically increasing lightness through the colormap\nwill be better interpreted by the viewer. A wonderful example of\nperceptually uniform colormaps is [colorcet]_.\n\nColor can be represented in 3D space in various ways. One way to represent color\nis using CIELAB. In CIELAB, color space is represented by lightness,\n$L^*$; red-green, $a^*$; and yellow-blue, $b^*$. The lightness\nparameter $L^*$ can then be used to learn more about how the matplotlib\ncolormaps will be perceived by viewers.\n\nAn excellent starting resource for learning about human perception of colormaps\nis from [IBM]_.\n\n\nClasses of colormaps\n====================\n\nColormaps are often split into several categories based on their function (see,\n*e.g.*, [Moreland]_):\n\n1. Sequential: change in lightness and often saturation of color\n   incrementally, often using a single hue; should be used for\n   representing information that has ordering.\n\n2. Diverging: change in lightness and possibly saturation of two\n   different colors that meet in the middle at an unsaturated color;\n   should be used when the information being plotted has a critical\n   middle value, such as topography or when the data deviates around\n   zero.\n\n3. Cyclic: change in lightness of two different colors that meet in\n   the middle and beginning/end at an unsaturated color; should be\n   used for values that wrap around at the endpoints, such as phase\n   angle, wind direction, or time of day.\n\n4. Qualitative: often are miscellaneous colors; should be used to\n   represent information which does not have ordering or\n   relationships.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# sphinx_gallery_thumbnail_number = 2\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom colorspacious import cspace_converter\nfrom collections import OrderedDict\n\ncmaps = OrderedDict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sequential\n----------\n\nFor the Sequential plots, the lightness value increases monotonically through\nthe colormaps. This is good. Some of the $L^*$ values in the colormaps\nspan from 0 to 100 (binary and the other grayscale), and others start around\n$L^*=20$. Those that have a smaller range of $L^*$ will accordingly\nhave a smaller perceptual range. Note also that the $L^*$ function varies\namongst the colormaps: some are approximately linear in $L^*$ and others\nare more curved.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cmaps['Perceptually Uniform Sequential'] = [\n            'viridis', 'plasma', 'inferno', 'magma', 'cividis']\n\ncmaps['Sequential'] = [\n            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',\n            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',\n            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sequential2\n-----------\n\nMany of the $L^*$ values from the Sequential2 plots are monotonically\nincreasing, but some (autumn, cool, spring, and winter) plateau or even go both\nup and down in $L^*$ space. Others (afmhot, copper, gist_heat, and hot)\nhave kinks in the $L^*$ functions. Data that is being represented in a\nregion of the colormap that is at a plateau or kink will lead to a perception of\nbanding of the data in those values in the colormap (see [mycarta-banding]_ for\nan excellent example of this).\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cmaps['Sequential (2)'] = [\n            'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',\n            'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',\n            'hot', 'afmhot', 'gist_heat', 'copper']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Diverging\n---------\n\nFor the Diverging maps, we want to have monotonically increasing $L^*$\nvalues up to a maximum, which should be close to $L^*=100$, followed by\nmonotonically decreasing $L^*$ values. We are looking for approximately\nequal minimum $L^*$ values at opposite ends of the colormap. By these\nmeasures, BrBG and RdBu are good options. coolwarm is a good option, but it\ndoesn't span a wide range of $L^*$ values (see grayscale section below).\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cmaps['Diverging'] = [\n            'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',\n            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Cyclic\n------\n\nFor Cyclic maps, we want to start and end on the same color, and meet a\nsymmetric center point in the middle. $L^*$ should change monotonically\nfrom start to middle, and inversely from middle to end. It should be symmetric\non the increasing and decreasing side, and only differ in hue. At the ends and\nmiddle, $L^*$ will reverse direction, which should be smoothed in\n$L^*$ space to reduce artifacts. See [kovesi-colormaps]_ for more\ninformation on the design of cyclic maps.\n\nThe often-used HSV colormap is included in this set of colormaps, although it\nis not symmetric to a center point. Additionally, the $L^*$ values vary\nwidely throughout the colormap, making it a poor choice for representing data\nfor viewers to see perceptually. See an extension on this idea at\n[mycarta-jet]_.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cmaps['Cyclic'] = ['twilight', 'twilight_shifted', 'hsv']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Qualitative\n-----------\n\nQualitative colormaps are not aimed at being perceptual maps, but looking at the\nlightness parameter can verify that for us. The $L^*$ values move all over\nthe place throughout the colormap, and are clearly not monotonically increasing.\nThese would not be good options for use as perceptual colormaps.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cmaps['Qualitative'] = ['Pastel1', 'Pastel2', 'Paired', 'Accent',\n                        'Dark2', 'Set1', 'Set2', 'Set3',\n                        'tab10', 'tab20', 'tab20b', 'tab20c']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Miscellaneous\n-------------\n\nSome of the miscellaneous colormaps have particular uses for which\nthey have been created. For example, gist_earth, ocean, and terrain\nall seem to be created for plotting topography (green/brown) and water\ndepths (blue) together. We would expect to see a divergence in these\ncolormaps, then, but multiple kinks may not be ideal, such as in\ngist_earth and terrain. CMRmap was created to convert well to\ngrayscale, though it does appear to have some small kinks in\n$L^*$.  cubehelix was created to vary smoothly in both lightness\nand hue, but appears to have a small hump in the green hue area.\n\nThe often-used jet colormap is included in this set of colormaps. We can see\nthat the $L^*$ values vary widely throughout the colormap, making it a\npoor choice for representing data for viewers to see perceptually. See an\nextension on this idea at [mycarta-jet]_.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cmaps['Miscellaneous'] = [\n            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',\n            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',\n            'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\nFirst, we'll show the range of each colormap. Note that some seem\nto change more \"quickly\" than others.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps.items())\ngradient = np.linspace(0, 1, 256)\ngradient = np.vstack((gradient, gradient))\n\n\ndef plot_color_gradients(cmap_category, cmap_list, nrows):\n    fig, axes = plt.subplots(nrows=nrows)\n    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)\n    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)\n\n    for ax, name in zip(axes, cmap_list):\n        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))\n        pos = list(ax.get_position().bounds)\n        x_text = pos[0] - 0.01\n        y_text = pos[1] + pos[3]/2.\n        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)\n\n    # Turn off *all* ticks & spines, not just the ones with colormaps.\n    for ax in axes:\n        ax.set_axis_off()\n\n\nfor cmap_category, cmap_list in cmaps.items():\n    plot_color_gradients(cmap_category, cmap_list, nrows)\n\nplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lightness of matplotlib colormaps\n=================================\n\nHere we examine the lightness values of the matplotlib colormaps.\nNote that some documentation on the colormaps is available\n([list-colormaps]_).\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "mpl.rcParams.update({'font.size': 12})\n\n# Number of colormap per subplot for particular cmap categories\n_DSUBS = {'Perceptually Uniform Sequential': 5, 'Sequential': 6,\n          'Sequential (2)': 6, 'Diverging': 6, 'Cyclic': 3,\n          'Qualitative': 4, 'Miscellaneous': 6}\n\n# Spacing between the colormaps of a subplot\n_DC = {'Perceptually Uniform Sequential': 1.4, 'Sequential': 0.7,\n       'Sequential (2)': 1.4, 'Diverging': 1.4, 'Cyclic': 1.4,\n       'Qualitative': 1.4, 'Miscellaneous': 1.4}\n\n# Indices to step through colormap\nx = np.linspace(0.0, 1.0, 100)\n\n# Do plot\nfor cmap_category, cmap_list in cmaps.items():\n\n    # Do subplots so that colormaps have enough space.\n    # Default is 6 colormaps per subplot.\n    dsub = _DSUBS.get(cmap_category, 6)\n    nsubplots = int(np.ceil(len(cmap_list) / dsub))\n\n    # squeeze=False to handle similarly the case of a single subplot\n    fig, axes = plt.subplots(nrows=nsubplots, squeeze=False,\n                             figsize=(7, 2.6*nsubplots))\n\n    for i, ax in enumerate(axes.flat):\n\n        locs = []  # locations for text labels\n\n        for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]):\n\n            # Get RGB values for colormap and convert the colormap in\n            # CAM02-UCS colorspace.  lab[0, :, 0] is the lightness.\n            rgb = cm.get_cmap(cmap)(x)[np.newaxis, :, :3]\n            lab = cspace_converter(\"sRGB1\", \"CAM02-UCS\")(rgb)\n\n            # Plot colormap L values.  Do separately for each category\n            # so each plot can be pretty.  To make scatter markers change\n            # color along plot:\n            # http://stackoverflow.com/questions/8202605/\n\n            if cmap_category == 'Sequential':\n                # These colormaps all start at high lightness but we want them\n                # reversed to look nice in the plot, so reverse the order.\n                y_ = lab[0, ::-1, 0]\n                c_ = x[::-1]\n            else:\n                y_ = lab[0, :, 0]\n                c_ = x\n\n            dc = _DC.get(cmap_category, 1.4)  # cmaps horizontal spacing\n            ax.scatter(x + j*dc, y_, c=c_, cmap=cmap, s=300, linewidths=0.0)\n\n            # Store locations for colormap labels\n            if cmap_category in ('Perceptually Uniform Sequential',\n                                 'Sequential'):\n                locs.append(x[-1] + j*dc)\n            elif cmap_category in ('Diverging', 'Qualitative', 'Cyclic',\n                                   'Miscellaneous', 'Sequential (2)'):\n                locs.append(x[int(x.size/2.)] + j*dc)\n\n        # Set up the axis limits:\n        #   * the 1st subplot is used as a reference for the x-axis limits\n        #   * lightness values goes from 0 to 100 (y-axis limits)\n        ax.set_xlim(axes[0, 0].get_xlim())\n        ax.set_ylim(0.0, 100.0)\n\n        # Set up labels for colormaps\n        ax.xaxis.set_ticks_position('top')\n        ticker = mpl.ticker.FixedLocator(locs)\n        ax.xaxis.set_major_locator(ticker)\n        formatter = mpl.ticker.FixedFormatter(cmap_list[i*dsub:(i+1)*dsub])\n        ax.xaxis.set_major_formatter(formatter)\n        ax.xaxis.set_tick_params(rotation=50)\n\n    ax.set_xlabel(cmap_category + ' colormaps', fontsize=14)\n    fig.text(0.0, 0.55, 'Lightness $L^*$', fontsize=12,\n             transform=fig.transFigure, rotation=90)\n\n    fig.tight_layout(h_pad=0.0, pad=1.5)\n    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Grayscale conversion\n====================\n\nIt is important to pay attention to conversion to grayscale for color\nplots, since they may be printed on black and white printers.  If not\ncarefully considered, your readers may end up with indecipherable\nplots because the grayscale changes unpredictably through the\ncolormap.\n\nConversion to grayscale is done in many different ways [bw]_. Some of the\nbetter ones use a linear combination of the rgb values of a pixel, but\nweighted according to how we perceive color intensity. A nonlinear method of\nconversion to grayscale is to use the $L^*$ values of the pixels. In\ngeneral, similar principles apply for this question as they do for presenting\none's information perceptually; that is, if a colormap is chosen that is\nmonotonically increasing in $L^*$ values, it will print in a reasonable\nmanner to grayscale.\n\nWith this in mind, we see that the Sequential colormaps have reasonable\nrepresentations in grayscale. Some of the Sequential2 colormaps have decent\nenough grayscale representations, though some (autumn, spring, summer,\nwinter) have very little grayscale change. If a colormap like this was used\nin a plot and then the plot was printed to grayscale, a lot of the\ninformation may map to the same gray values. The Diverging colormaps mostly\nvary from darker gray on the outer edges to white in the middle. Some\n(PuOr and seismic) have noticeably darker gray on one side than the other\nand therefore are not very symmetric. coolwarm has little range of gray scale\nand would print to a more uniform plot, losing a lot of detail. Note that\noverlaid, labeled contours could help differentiate between one side of the\ncolormap vs. the other since color cannot be used once a plot is printed to\ngrayscale. Many of the Qualitative and Miscellaneous colormaps, such as\nAccent, hsv, and jet, change from darker to lighter and back to darker gray\nthroughout the colormap. This would make it impossible for a viewer to\ninterpret the information in a plot once it is printed in grayscale.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "mpl.rcParams.update({'font.size': 14})\n\n# Indices to step through colormap.\nx = np.linspace(0.0, 1.0, 100)\n\ngradient = np.linspace(0, 1, 256)\ngradient = np.vstack((gradient, gradient))\n\n\ndef plot_color_gradients(cmap_category, cmap_list):\n    fig, axes = plt.subplots(nrows=len(cmap_list), ncols=2)\n    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99,\n                        wspace=0.05)\n    fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6)\n\n    for ax, name in zip(axes, cmap_list):\n\n        # Get RGB values for colormap.\n        rgb = cm.get_cmap(plt.get_cmap(name))(x)[np.newaxis, :, :3]\n\n        # Get colormap in CAM02-UCS colorspace. We want the lightness.\n        lab = cspace_converter(\"sRGB1\", \"CAM02-UCS\")(rgb)\n        L = lab[0, :, 0]\n        L = np.float32(np.vstack((L, L, L)))\n\n        ax[0].imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))\n        ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.)\n        pos = list(ax[0].get_position().bounds)\n        x_text = pos[0] - 0.01\n        y_text = pos[1] + pos[3]/2.\n        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)\n\n    # Turn off *all* ticks & spines, not just the ones with colormaps.\n    for ax in axes.flat:\n        ax.set_axis_off()\n\n    plt.show()\n\n\nfor cmap_category, cmap_list in cmaps.items():\n\n    plot_color_gradients(cmap_category, cmap_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Color vision deficiencies\n=========================\n\nThere is a lot of information available about color blindness (*e.g.*,\n[colorblindness]_). Additionally, there are tools available to convert images\nto how they look for different types of color vision deficiencies.\n\nThe most common form of color vision deficiency involves differentiating\nbetween red and green. Thus, avoiding colormaps with both red and green will\navoid many problems in general.\n\n\nReferences\n==========\n\n.. [colorcet] https://colorcet.pyviz.org\n.. [Ware] http://ccom.unh.edu/sites/default/files/publications/Ware_1988_CGA_Color_sequences_univariate_maps.pdf\n.. [Moreland] http://www.kennethmoreland.com/color-maps/ColorMapsExpanded.pdf\n.. [list-colormaps] https://gist.github.com/endolith/2719900#id7\n.. [mycarta-banding] https://mycarta.wordpress.com/2012/10/14/the-rainbow-is-deadlong-live-the-rainbow-part-4-cie-lab-heated-body/\n.. [mycarta-jet] https://mycarta.wordpress.com/2012/10/06/the-rainbow-is-deadlong-live-the-rainbow-part-3/\n.. [kovesi-colormaps] https://arxiv.org/abs/1509.03700\n.. [bw] http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/\n.. [colorblindness] http://www.color-blindness.com/\n.. [IBM] https://doi.org/10.1109/VISUAL.1995.480803\n.. [palettable] https://jiffyclub.github.io/palettable/\n\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
